﻿using IXION.BLOG.COMMON.PASSWORD;
using IXION.BLOG.DOMAIN.USER;
using IXION.BLOG.SERVICE.ADMIN;
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.SessionState;

namespace IXION.BLOG.WEB.UI.Admin.Handler
{
    /// <summary>
    /// AdminActionHandler 的摘要说明
    /// 此一般处理程序用于处理管理后台的各种异步提交事件
    /// </summary>
    public class AdminActionHandler : IHttpHandler,IRequiresSessionState 
    {
        HttpRequest Requset;
        HttpResponse Response;
        HttpSessionState Session;
        protected AdminService service = new AdminService();
        public void ProcessRequest(HttpContext context)
        {
            Init();
            context.Response.ContentType = "text/plain";
            string action = Requset["action"];
            string msg = "did nothing but AdminActionHandler running";
            switch (action)
            {
                case "Login":
                    msg = DoAdminLogin();
                    break;
                default:
                    break;
            }
            context.Response.Write(msg);
        }
        /// <summary>
        /// 处理登陆事件 并且将结果返回便于在js中获取结果进行相关处理
        /// </summary>
        /// <returns></returns>
        private string DoAdminLogin()
        {
            string userName = Requset["user"];
            string password = Requset["password"];
            if(userName == null || userName.Trim()==""){
                return "用户名为空";
            }
            if(password == null || password == ""){
                return "请输入密码";
            }
            User user = service.GetUserByUserName(userName);
            if (user == null)
            {
                return "不存在该用户，请重新输入用户名";
            }
            else {
                bool flag = (PasswordUtils.MD5(password) == user.Password);
                //将登陆状态保持下来
                if(flag){
                    Session["User"] = user;
                    Session["Admin"] = true;
                }
                return flag.ToString();
            }
            //throw new NotImplementedException();
        }
        /// <summary>
        /// 初始化request response session方便在方法中使用
        /// </summary>
        private void Init()
        {
            Requset = HttpContext.Current.Request;
            Response = HttpContext.Current.Response;
            Session = HttpContext.Current.Session;
            //throw new NotImplementedException();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}